package hu.imind.phonecalc.entity;

import hu.imind.phonecalc.client.dto.Call;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@SuppressWarnings("serial")
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Bill implements Serializable {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
    @Persistent
    private String date;
    @Persistent
    private List<CallData> calls;
    
    public void addCalls(List<Call> callsParam) {
        if (calls == null) {
            calls = new ArrayList<CallData>();
        }
        for (Call call : callsParam) {
            calls.add(new CallData(call));
        }
    }
    
    public void setKey(String email) {
        key = createKey(email, date);
    }
    
    public static Key createKey(String email, String date) {
        Key k = new KeyFactory.Builder(
                PhoneCalcUser.class.getSimpleName(), 
                email)
            .addChild(Bill.class.getSimpleName(), "D" + date)
            .getKey();
        return k;
    }


    public List<Call> getCallList() {
        if (calls == null) {
            calls = new ArrayList<CallData>();
        }
        ArrayList<Call> res = new ArrayList<Call>();
        if (calls.size() > 0) {
            for(CallData ec: calls) {
                Call c = ec.getCall();
                res.add(c);
            }
            return res;
        } else {
            return null;
        }
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public List<CallData> getCalls() {
        return calls;
    }

    public void setCalls(List<CallData> calls) {
        this.calls = calls;
    }
}
